import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import { SoftwareInfo, SoftwareService } from '../../services/software.service';
import { NgModel, NgForm } from '@angular/forms';
import { EditBase } from 'app/modules/base/edit-base';

@Component({
	selector: 'm-edit-card',
	templateUrl: './edit-card.component.html',
	styleUrls: ['./edit-card.component.scss'],
})
export class EditCardComponent extends EditBase implements OnInit {
	constructor(private softManager: SoftwareService) {
		super();
	}
	@Input() soft: SoftwareInfo;
	@Input() area_id: number;
	@Output() cancel = new EventEmitter();
	@Output() saved = new EventEmitter();
	@ViewChild(NgForm) form: NgForm;
	@ViewChild('formRef') formRef: ElementRef<HTMLFormElement>;

	category$ = this.softManager.category();
	preview: string;

	ngOnInit() {
		setTimeout(() => {
			this.preview = this.soft.icon;
			const value = this.toFormValue(this.soft);
			this.form.form.patchValue({ ...value, icon: '' });
		});
	}
	async submit() {
		this.form.onSubmit(null);
		if (this.form.invalid) {
			return;
		}
		const data = new FormData(this.formRef.nativeElement);
		await this.softManager.updateWithAreaId(this.area_id, data);
		this.saved.next();
	}
}
